import 'package:aio/aio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:app/generated/app_strings.dart';
import 'package:app/src/http/model/material_requisition_model.dart';
import 'package:app/src/ui/dialog/dailog.dart';
import 'package:app/src/ui/route/helper/route_helper.dart';
import 'package:app/src/ui/route/works/public/items/ui_base.dart';
import 'package:app/src/ui/route/works/public/items/ui_card.dart';

import '../../../../../http/bean/works_2023/purcontract_bean.dart';
import '../../../../../http/bean/works_2023/purorderInfo_bean.dart';
import '../../../../../http/bean/worksdo/material_requisition_bean.dart';
import '../../../../../http/bean/wroks/dispatchingaudit_bean.dart';
import '../../../../../http/bean/ywx_limit.dart';
import '../../../../../utils/a_combined_utils.dart';
import '../../../../app_ui.dart';

///采购合同审核：物料信息
class UiPurContractAuditForm {
  static bool _isForceCompare = false;

  static Widget build(
      BuildContext context, PurContractBean? materialInfo, YwxItem item,
      {String? title, PurContractBean? oldData}) {
    // print("新数据：\n${GsonUtils.listToJson(materialInfo?.PurContractList)}");
    // print("旧数据：\n${GsonUtils.listToJson(oldData?.PurContractList)}");
    // print("新数据");
    // materialInfo?.PurContractList?.forEach((element) {
    //   print("${element?.PurCode}\t${element?.POListId}");
    // });
    // print("旧数据");
    // oldData?.PurContractList?.forEach((element) {
    //   print("${element?.PurCode}\t${element?.POListId}");
    // });
    return StatefulBuilder(builder: (context, setState) {
      List<Widget> children = [];
      if (StringUtils.isEmpty(title)) {
        title = AppStrings.of(context).MaterialInfo; //物料信息
      }
      var isGrey = false;
      _isForceCompare = false; //是否强制对比，新旧数据只要不一样就对比。（null和空字符也对比）
      if (oldData != null) {
        _isForceCompare = true;
      }
      children.add(UiBase.title(context, title,
          bottom: AppEdgeInsets.margin_bottom)); //标题
      children.add(UiBase.item(context, AppStrings.of(context).PurBodyCode,
          materialInfo?.PurBodyCode, null,
          isGrey: isGrey,
          isAllowEmpty: true,
          isStart: false,
          isForceCompare: false)); //子合同编号 fixme 不做对比
      children.add(UiBase.item(context, AppStrings.of(context).ContractOutCode,
          materialInfo?.OutCode, oldData?.OutCode,
          isGrey: isGrey,
          isAllowEmpty: true,
          isStart: false,
          isForceCompare: _isForceCompare)); //子合同外部编号
      children.add(UiBase.item(context, AppStrings.of(context).SignDateDate,
          materialInfo?.getSignDateTime(), oldData?.getSignDateTime(),
          isGrey: isGrey,
          isAllowEmpty: true,
          isStart: false,
          isForceCompare: _isForceCompare)); //签订日期*
      children.add(UiBase.item(context, AppStrings.of(context).DeliveryDateTime,
          materialInfo?.getDeliveryDateTime(), oldData?.getDeliveryDateTime(),
          isGrey: isGrey,
          isAllowEmpty: true,
          isStart: false,
          isForceCompare: _isForceCompare)); //要货日期*
      ///查看附件
      bool titleRed = false;
      var fileInfo = materialInfo?.getBodyFileInfo().toString();
      var oldFileInfo = oldData?.getBodyFileInfo().toString();
      if (oldFileInfo != null && fileInfo != oldFileInfo) {
        titleRed = true;
      }
      children.add(
          UiBase.itemWithButon(context, AppStrings.of(context).ToView2, () {
        if (StringUtils.isEmpty(materialInfo?.getBodyFileInfo())) {
          AppDialog.showDialogWithInfo(context,
              content: AppStrings.of(context).AttachmentEmpty); //当前附件为空!
          return;
        }
        AppRouteHelper.goPurcontractAuditDetailsFujianRoute(
            context, item, materialInfo?.getBodyFileInfo());
      }, margin: EdgeInsets.only(top: 8, bottom: 8), textStyleRed: titleRed));
      children.add(_table(context, materialInfo!, item, oldData: oldData));
      var column = UiBase.column(context, children);
      var card = UiCard.build(context, column);
      return card;
    });
  }

  ///fixme Table表格里的行TabRow;每一行的表格数量必须相等。不然报错。
  ///fixme table嵌套table实现单元格合并。

  //表格线条颜色
  static Color _BorderColor = Colors.black12;

  //表格线条宽度
  static double _width = 1;

  ///背景色表格标题
  static Color _backgroundColorWithTableTitle = Colors.black12;
  static Color _backgroundColorWithWhite = Colors.white;
  static Color _backgroundColorWithGrey = ColorUtils.parseColor("#F7F6F3");
  static StateSetter? _setState = null;

  static Widget _table(
      BuildContext context, PurContractBean materialInfo, YwxItem item,
      {PurContractBean? oldData}) {
    if (materialInfo?.PurContractList == null ||
        materialInfo!.PurContractList!.length <= 0) {
      return LibUi.getEmptyView();
    }
    //fixme 表格
    return StatefulBuilder(builder: (context, setState) {
      _setState = setState;
      //可以水平滑动的表格
      var scrolltable =
          _scrolltable(context, materialInfo, item, oldData: oldData);
      //水平滑动效果
      var singleChildScrollView = SingleChildScrollView(
          child: scrolltable, scrollDirection: Axis.horizontal);
      return Center(
        child: Container(
          child: singleChildScrollView,
          //width: 2400,
        ),
      );
    });
  }

  static bool isNewUnit = false; //是否显示新单位和（包数量，每包数量）
  ///水平滑动表格
  static Widget _scrolltable(
      BuildContext context, PurContractBean materialInfo, YwxItem item,
      {PurContractBean? oldData}) {
    if (materialInfo.PurContractList == null ||
        materialInfo.PurContractList!.length <= 0) {
      return AppUi.getEmptyView();
    }
    List<PurContractListBean> allDatas = materialInfo.PurContractList!;
    List<List<PurContractListBean>?> listDatas =
        materialInfo.getPurContractLists();

    // listDatas?.addAll(listDatas);//fixme 测试多数据，记得删除
    // List<List<PurContractListBean>?> listDatas2 =[];
    // listDatas?.forEach((element) {
    //   listDatas2.add(element);
    // });
    // listDatas?.addAll(listDatas2);

    List<List<PurContractListBean>?>? oldListDatas =
        oldData?.getPurContractLists();

    var firstData = allDatas[0];
    var children = <TableRow>[];
    var isMT01 = firstData.isMT01(); //判断是否为原片
    _index = 0; //fixme 总序号
    //第一行标题栏
    List<Widget> titleChildren = [];
    titleChildren.add(_titleSerial(context, firstData, isMT01)); //序号
    titleChildren
        .add(_text(context, AppStrings.of(context).PurOrderCode)); //采购单号
    titleChildren.add(_titleAll(context, firstData, isMT01)); //标题
    var tableRow = TableRow(
        decoration: BoxDecoration(color: _backgroundColorWithTableTitle),
        children: titleChildren);
    children.add(tableRow);
    //第二行，内容行。
    for (int i = 0; i < listDatas.length; i++) {
      var datas = listDatas[i];
      var data = datas![0];

      List<PurContractListBean>? oldDatas = null;
      if (oldListDatas != null && oldListDatas!.length > i) {
        oldDatas = oldListDatas[i];
      }

      List<Widget> rowChildren = [];
      //序号
      rowChildren.add(Container(
        // color: Colors.yellow,
        alignment: Alignment.center,
        child: _contentSerial(context, datas, oldDatas, oldData),
      ));
      // rowChildren.add(Row(
      //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
      //   children: [_contentSerial(context, datas, oldDatas, oldData)],
      // ));
      //PurOrderCode 采购单号
      var PurOrderCode = _text(context, "${data.PurOrderCode}",
          isForceCompare: false); //fixme 不做标记
      rowChildren.add(PurOrderCode);
      //物料信息内容
      rowChildren.add(_contentAll(context, datas, firstData, isMT01,
          oldDatas: oldDatas, mOldData: oldData));
      var tableRow = TableRow(
        // decoration: BoxDecoration(color: _getColor(_index + 1)),
        decoration: BoxDecoration(color: _getColor(i)),
        children: rowChildren,
      );
      children.add(tableRow);
    }
    //第三行，合计
    List<Widget> totalChildren = [];
    totalChildren.add(_totalSerial(context)); //序号
    totalChildren.add(_text(context, AppStrings.of(context).ACombined)); //合计
    totalChildren.add(_totalAll(context, allDatas, firstData, isMT01)); //内容
    var totaltableRow = TableRow(
        decoration: BoxDecoration(color: _backgroundColorWithTableTitle),
        children: totalChildren);
    children.add(totaltableRow);
    var table = Table(
      border: TableBorder.all(
          color: _BorderColor, width: _width, style: BorderStyle.solid),
      defaultVerticalAlignment: TableCellVerticalAlignment.middle,
      columnWidths: {
        0: FixedColumnWidth(80),
        1: FixedColumnWidth(200),
        2: FixedColumnWidth(2200),
      },
      children: children,
    );
    return table;
  }

  static FixedColumnWidth _FixedColumnWidth({double width = 100}) {
    return FixedColumnWidth(width);
  }

  static Map<int, TableColumnWidth>? _columnWidths() {
    return {
      0: FixedColumnWidth(200),
      1: _FixedColumnWidth(),
      2: _FixedColumnWidth(width: 200),
      3: _FixedColumnWidth(width: 150),
      4: _FixedColumnWidth(),
      5: _FixedColumnWidth(),
      6: _FixedColumnWidth(),
      7: _FixedColumnWidth(),
      8: _FixedColumnWidth(),
      9: _FixedColumnWidth(),
      10: _FixedColumnWidth(),
      11: _FixedColumnWidth(),
      12: _FixedColumnWidth(),
      13: _FixedColumnWidth(),
      14: _FixedColumnWidth(),
      15: _FixedColumnWidth(),
      16: _FixedColumnWidth(),
      17: _FixedColumnWidth(),
      18: _FixedColumnWidth(),
      19: _FixedColumnWidth(),
      20: _FixedColumnWidth(),
      21: _FixedColumnWidth(),
      22: _FixedColumnWidth(),
      23: _FixedColumnWidth(),
      24: _FixedColumnWidth(),
    };
  }

  ///内部嵌套表格(序号)
  static Widget _titleSerial(
      BuildContext context, PurContractListBean firstData, bool isMT01) {
    List<Widget> titleChildren = [];
    titleChildren.add(_text(context, AppStrings.of(context).TheSerial)); //序号
    var table = Table(
      border: TableBorder.symmetric(
        inside: BorderSide(
            color: _BorderColor, width: _width, style: BorderStyle.solid),
      ),
      children: [
        TableRow(children: titleChildren),
      ],
      defaultVerticalAlignment: TableCellVerticalAlignment.middle,
    );
    return table;
  }

  ///内部嵌套表格(标题)
  static Widget _titleAll(
      BuildContext context, PurContractListBean firstData, bool isMT01) {
    List<Widget> titleChildren = [];
    titleChildren
        .add(_text(context, AppStrings.of(context).PurchaseOrderNumber)); //请购单号
    titleChildren
        .add(_text(context, AppStrings.of(context).TypeOfMaterial)); //物料类型
    titleChildren
        .add(_text(context, AppStrings.of(context).MaterialName3)); //物料名称
    titleChildren
        .add(_text(context, AppStrings.of(context).MaterialCode)); //物料编码
    titleChildren
        .add(_text(context, AppStrings.of(context).Width_Height2)); //型号
    if (isMT01) {
      titleChildren
          .add(_text(context, AppStrings.of(context).Specifications)); //规格
    } else {
      if (firstData.Iswidth2()) {
        titleChildren.add(_text(context, AppStrings.of(context).ItemWidth)); //宽
      }
      if (firstData.Isheight2()) {
        titleChildren
            .add(_text(context, AppStrings.of(context).ItemHeight)); //高
      }
      if (firstData.Islength2()) {
        titleChildren.add(_text(context, AppStrings.of(context).long)); //长
      }
      if (firstData.Isthickness2()) {
        titleChildren
            .add(_text(context, AppStrings.of(context).thickness2)); //厚
      }
      if (firstData.Isquantity2()) {
        titleChildren.add(_text(context, AppStrings.of(context).ItemNum)); //数量
      }
      if (!firstData.isMT01() && isNewUnit) {
        //辅料，五金；显示；包数量，和每包数量。
        titleChildren.add(_text(context, AppStrings.of(context).PackageCount,
            isStart: true)); //包数量
        titleChildren.add(_text(
            context, AppStrings.of(context).PackageListCount,
            isStart: true)); //每包数量
      }
    }
    titleChildren.add(
        _text(context, AppStrings.of(context).PDMinNum, isStart: false)); //请购数量
    titleChildren
        .add(_text(context, AppStrings.of(context).Unit, isStart: false)); //单位
    titleChildren.add(_text(context, AppStrings.of(context).QuantityPurchased2,
        isStart: false)); //采购数量
    titleChildren.add(_text(context, AppStrings.of(context).Quantity3,
        isStart: false)); //已申请数量
    if (isMT01) {
      titleChildren.add(_text(context, AppStrings.of(context).tons)); //顿重
      titleChildren
          .add(_text(context, AppStrings.of(context).tonsprice)); //顿重单价
    }
    if (isMT01) {
      titleChildren.add(_text(context, AppStrings.of(context).Area)); //面积
      titleChildren
          .add(_text(context, AppStrings.of(context).areaprice)); //折算面积单价
    }
    if (firstData.isPrice()) {
      titleChildren.add(
          _text(context, AppStrings.of(context).Price2, isStart: false)); //单价
    }
    titleChildren.add(_text(context, AppStrings.of(context).DAmount)); //金额
    if (isMT01) {
      titleChildren
          .add(_text(context, AppStrings.of(context).QualityGrade2)); //质量等级
    }
    titleChildren
        .add(_text(context, AppStrings.of(context).ManufacturerName)); //品牌
    titleChildren.add(_text(context, AppStrings.of(context).Note)); //备注
    var table = Table(
      border: TableBorder.symmetric(
        inside: BorderSide(
            color: _BorderColor, width: _width, style: BorderStyle.solid),
      ),
      children: [
        TableRow(children: titleChildren),
      ],
      columnWidths: _columnWidths(),
      defaultVerticalAlignment: TableCellVerticalAlignment.middle,
    );
    return table;
  }

  ///下标；这里主要作为总序号使用。
  static int _index = 0; //fixme 使用的使用，第一次记得设置为0；

  ///内部嵌套表格(序号)
  ///datas 数据
  ///mOldData 总的老数据，用于判断是否需要对比；如果为null就不需要对比。
  static Widget _contentSerial(
      BuildContext context,
      List<PurContractListBean> datas,
      List<PurContractListBean>? oldDatas,
      PurContractBean? mOldData) {
    // print("=======================新数据$datas");
    // datas?.forEach((element) {
    //   print(
    //       "PurOrderCode:${element.PurOrderCode}\tPOListId:${element.POListId}");
    // });
    // print("=======================旧数据$oldDatas");
    // oldDatas?.forEach((element) {
    //   print(
    //       "PurOrderCode:${element.PurOrderCode}\tPOListId:${element.POListId}");
    // });
    var children = <TableRow>[];
    for (int i = 0; i < datas.length; i++) {
      var data = datas[i];
      PurContractListBean? oldData = null;
      var POListId = data.POListId; //fixme 用id去查找旧数据；新旧数据组的顺序可能不一致。
      if (oldDatas != null && oldDatas.length > i) {
        oldDatas.forEach((element) {
          if (element.POListId == POListId) {
            oldData = element;
          }
        });
        //oldData = oldDatas[i];//fixme 新旧数据顺序不一致；不能通过下标来标识。
      }

      ///这里全局搜索必须放在上面if (oldDatas != null && oldDatas.length > i)循环之后；上次就是犯了这错误；
      ///fixme 这里直接通过mOldData全局搜索，更准确。
      if (oldData == null) {
        mOldData?.PurContractList?.forEach((element) {
          if (element.POListId == POListId) {
            oldData = element;
          }
        });
      }
      _index++; //fixme 序号加一
      List<Widget> rowChildren = [];
      //序号
      Widget TheSerial;
      if (mOldData != null && oldData == null) {
        //fixme 旧数据找不到，说明是新增的数据;序号直接变红。
        TheSerial = _text(context, "$_index(${AppStrings.of(context).New})",
            isRed: true);
      } else {
        TheSerial = _text(context, "$_index");
      }
      rowChildren.add(Center(
        child: TheSerial,
      ));
      var tableRow = TableRow(
          // decoration: BoxDecoration(color: _getColor(_index + 1)),
          // decoration: BoxDecoration(color: _getColor(i)),
          children: rowChildren);
      children.add(tableRow);
    }
    var table = Table(
      border: TableBorder.symmetric(
          inside: BorderSide(
              color: _BorderColor, width: _width, style: BorderStyle.solid),
          outside: BorderSide.none),
      children: children,
      defaultVerticalAlignment: TableCellVerticalAlignment.middle,
    );
    return table;
  }

  ///内部嵌套表格(内容)
  ///datas 数据
  static Widget _contentAll(
      BuildContext context,
      List<PurContractListBean> datas,
      PurContractListBean firstData,
      bool isMT01,
      {List<PurContractListBean>? oldDatas,
      PurContractBean? mOldData}) {
    var children = <TableRow>[];
    for (int i = 0; i < datas.length; i++) {
      var data = datas[i];
      PurContractListBean? oldData = null;
      var POListId = data.POListId; //fixme 用id去查找旧数据；新旧数据组的顺序可能不一致。
      if (oldDatas != null && oldDatas.length > i) {
        oldDatas.forEach((element) {
          if (element.POListId == POListId) {
            oldData = element;
          }
        });
        //oldData = oldDatas[i];
      }

      ///这里全局搜索必须放在上面if (oldDatas != null && oldDatas.length > i)循环之后；上次就是犯了这错误；
      ///fixme 这里直接通过mOldData全局搜索，更准确。
      if (oldData == null) {
        mOldData?.PurContractList?.forEach((element) {
          if (element.POListId == POListId) {
            oldData = element;
          }
        });
      }
      var _isForceCompare2 = _isForceCompare;
      if (oldData == null) {
        _isForceCompare2 = false; //fixme 旧数据为空，就不做强制对比(因为是新数据)。
      }
      List<Widget> rowChildren = [];
      //请购单号 PurCode
      var PurCode = _text(context, "${data.PurCode}",
          oldText: "${oldData?.PurCode}", isForceCompare: _isForceCompare2);
      rowChildren.add(PurCode);
      //物料类型
      var MaterialType = _text(context, "${data.getMaterialTypeName(context)}",
          oldText: "${oldData?.getMaterialTypeName(context)}",
          isForceCompare: _isForceCompare2);
      rowChildren.add(MaterialType);
      //物料名称
      var MaterialName = _text(context, "${data.MaterialName}",
          oldText: "${oldData?.MaterialName}",
          isForceCompare: _isForceCompare2);
      rowChildren.add(MaterialName);
      //物料编码
      var MaterialCode = _text(context, "${data.MaterialCode}",
          oldText: "${oldData?.MaterialCode}",
          isForceCompare: _isForceCompare2);
      rowChildren.add(MaterialCode);
      //型号
      var Size = _text(context, "${data.Size}",
          oldText: "${oldData?.Size}", isForceCompare: _isForceCompare2);
      rowChildren.add(Size);
      if (isMT01) {
        //规格
        var Width_Height = StatefulBuilder(
          builder: (contxet, setState) {
            var Size =
                "${StringUtils.toStringAsDecimal(data?.Width)} X ${StringUtils.toStringAsDecimal(data?.Height)}";
            var oldSize = "";
            if (oldData != null && oldData?.Width != null) {
              oldSize = "${oldData?.Width} X ${oldData?.Height}";
            }
            return _text(context, Size,
                oldText: "${oldSize}", isForceCompare: _isForceCompare2);
          },
        );
        rowChildren.add(Width_Height);
      } else {
        if (firstData.Iswidth2()) {
          //宽
          // var ItemWidth = _text(
          //     context, StringUtils.toStringAsDecimal(data?.Width),
          //     oldText: "${StringUtils.toStringAsDecimal(oldData?.Width)}",
          //     isForceCompare: _isForceCompare2);
          var _w = "${data?.getWidthInput()}${data?.WidthUnit}";
          var _w2 = "${oldData?.getWidthInput()}${data?.WidthUnit}";
          var ItemWidth = _text(context, _w,
              oldText: _w2, isForceCompare: _isForceCompare2);
          rowChildren.add(ItemWidth);
        }
        if (firstData.Isheight2()) {
          //高
          // var ItemHeight = _text(
          //     context, StringUtils.toStringAsDecimal(data?.Height),
          //     oldText: "${StringUtils.toStringAsDecimal(oldData?.Height)}",
          //     isForceCompare: _isForceCompare2);
          var _1 = "${data?.getHeightInput()}${data?.HeightUnit}";
          var _2 = "${oldData?.getHeightInput()}${data?.HeightUnit}";
          var _v =
              _text(context, _1, oldText: _2, isForceCompare: _isForceCompare2);
          rowChildren.add(_v);
        }
        if (firstData.Islength2()) {
          //长
          // var long = _text(
          //     context, StringUtils.toStringAsDecimal(data?.lengths),
          //     oldText: "${oldData?.lengths}", isForceCompare: _isForceCompare2);
          // rowChildren.add(long);
          var _1 = "${data?.getLengthsInput()}${data?.LengthUnit}";
          var _2 = "${oldData?.getLengthsInput()}${data?.LengthUnit}";
          var _v =
              _text(context, _1, oldText: _2, isForceCompare: _isForceCompare2);
          rowChildren.add(_v);
        }
        if (firstData.Isthickness2()) {
          //厚
          // var thickness = _text(
          //     context, StringUtils.toStringAsDecimal(data?.Thickness2),
          //     oldText: "${oldData?.Thickness2}",
          //     isForceCompare: _isForceCompare2);
          // rowChildren.add(thickness);
          var _1 = "${data?.getThicknessInput()}${data?.ThicknessUnit}";
          var _2 = "${oldData?.getThicknessInput()}${data?.ThicknessUnit}";
          var _v =
              _text(context, _1, oldText: _2, isForceCompare: _isForceCompare2);
          rowChildren.add(_v);
        }
        if (firstData.Isquantity2()) {
          //数量
          // var ItemNum = _text(
          //     context, StringUtils.toStringAsDecimal(data?.numbers),
          //     oldText: "${oldData?.numbers}", isForceCompare: _isForceCompare2);
          var ItemNum = _text(context, data?.getNumbersStrAndUnit(),
              oldText: "${oldData?.getNumbersStrAndUnit()}",
              isForceCompare: _isForceCompare2);
          rowChildren.add(ItemNum);
        }
        if (!firstData.isMT01() && isNewUnit) {
          //fixme 辅料，五金；显示；包数量，和每包数量。
          //包数量
          var PackageCount = StatefulBuilder(builder: (contxet, setState) {
            // PackageCountSetState = setState;
            // TextEditingController? _controller;
            // var _key = "PackageCount:${data?.ListId}${data?.index}_${i}";
            var PackageCount = UiBase.itemWithSigleEdit(
                context, StringUtils.toStringAsDecimal(data?.PackageCount),
                unit: data?.PackageUnit,
                readOnly: true,
                // onController: (value) {
                //   _controller = value;
                // },
                // mtextSelection: getTextSelection(_key),
                // focusNode: FocusNodeManager.getFocusNode(_key).addListener(
                //       (value) {
                //     if (value) {
                //       //聚焦
                //       setTextSelection(_key, _controller?.selection); //记录焦点位置
                //     } else {
                //       //失去焦点
                //       setTextSelection(_key, null);
                //     }
                //   },
                // ),
                isAllowEmpty: true,
                isDecimal: true,
                isNegative: false,
                isLine: true, onChanged: (value) {
              if (StringUtils.isEmpty(value)) {
                data?.PackageCount = "0"; //不能为空，为空，提交接口会报数据格式错误。
              } else {
                data?.PackageCount = value;
              }
              // isDemandNumUpdate = false;
              // data?.DemandNum = DecimalUtils.multiply(
              //     data?.toDouble(data?.PackageCount).toString(),
              //     data
              //         ?.toDouble(data?.PackageListCount)
              //         .toString()); //fixme 申请数量就等于包数量*每包数量
              // data?.MinNum = data?.DemandNum;
              // NumberOfApplications?.call(() {}); //申请数量
              ///sizeSetState?.call(() {}); //规格更新
              // getStockNum(
              //     context, CurrentInventorySetState, MaterialCodeSetState, data);

              ///库存数量
            });
            return PackageCount;
          });
          rowChildren.add(PackageCount);

          //每包数量
          var PackageListCount = StatefulBuilder(builder: (contxet, setState) {
            // PackageListCountSetState = setState;
            // TextEditingController? _controller;
            // var _key = "PackageListCount:${data?.ListId}${data?.index}_${i}";
            var _unit = "${data?.MainUnit}/${data?.PackageUnit}";
            var PackageListCount = UiBase.itemWithSigleEdit(
                context, StringUtils.toStringAsDecimal(data?.PackageListCount),
                unit: _unit,
                readOnly: true,
                // onController: (value) {
                //   _controller = value;
                // },
                // mtextSelection: getTextSelection(_key),
                // focusNode: FocusNodeManager.getFocusNode(_key).addListener(
                //       (value) {
                //     if (value) {
                //       //聚焦
                //       setTextSelection(_key, _controller?.selection); //记录焦点位置
                //     } else {
                //       //失去焦点
                //       setTextSelection(_key, null);
                //     }
                //   },
                // ),
                isAllowEmpty: true,
                isDecimal: true,
                isNegative: false,
                isLine: true, onChanged: (value) {
              if (StringUtils.isEmpty(value)) {
                data?.PackageListCount = "0"; //不能为空，为空，提交接口会报数据格式错误。
              } else {
                data?.PackageListCount = value;
              }
              // isDemandNumUpdate = false;
              // data?.DemandNum = DecimalUtils.multiply(
              //     data?.toDouble(data?.PackageCount).toString(),
              //     data
              //         ?.toDouble(data?.PackageListCount)
              //         .toString()); //fixme 申请数量就等于包数量*每包数量
              // data?.MinNum = data?.DemandNum;
              // NumberOfApplications?.call(() {}); //申请数量
              ///sizeSetState?.call(() {}); //规格更新
              // getStockNum(
              //     context, CurrentInventorySetState, MaterialCodeSetState, data);

              ///库存数量
            });
            return PackageListCount;
          });
          rowChildren.add(PackageListCount);
        }
      }
      //fixme 请购数量 ========================================================================
      var MainNum = StatefulBuilder(
        builder: (contxet, setState) {
          // var isRed = UiBase.isNotSame(data?.POMinNum, oldData?.POMinNum);
          // return UiBase.itemWithSigleEdit(context, data?.POMinNum,
          //     isAllowEmpty: true,
          //     isDecimal: true,
          //     readOnly: true,
          //     isNegative: false,
          //     isRed: isRed);
          //print("请购数量：${data?.POListId}\t${oldData?.POListId}\t${data?.POMinNum}\t${oldData?.POMinNum}\t$_isForceCompare\t${oldData}");
          return UiBase.itemWithCompare(
              context,
              StringUtils.toStringAsDecimal(data?.POMinNum),
              StringUtils.toStringAsDecimal(oldData?.POMinNum),
              horizon: false,
              isForceCompare: _isForceCompare2);
        },
      );
      rowChildren.add(MainNum);
      //单位
      var POMainUnit = StatefulBuilder(
        builder: (contxet, setState) {
          // var isRed = UiBase.isNotSame(data?.POMainUnit, oldData?.POMainUnit);
          // return UiBase.itemWithSigleEdit(context, data?.POMainUnit,
          //     isAllowEmpty: true,
          //     isDecimal: true,
          //     readOnly: true,
          //     isNegative: false,
          //     isRed: isRed);
          return UiBase.itemWithCompare(
              context, data?.POMainUnit, oldData?.POMainUnit,
              horizon: false, isForceCompare: _isForceCompare2);
        },
      );
      rowChildren.add(POMainUnit);
      //fixme 采购数量 ============================================================================
      var NumberOfApplications3 = StatefulBuilder(
        builder: (contxet, setState) {
          // var isRed = UiBase.isNotSame(data?.MainNum, oldData?.MainNum);
          // return UiBase.itemWithSigleEdit(context, data?.MainNum,
          //     isAllowEmpty: true,
          //     isDecimal: true,
          //     readOnly: true,
          //     isNegative: false,
          //     isRed: isRed);
          return UiBase.itemWithCompare(
              context,
              StringUtils.toStringAsDecimal(data?.MainNum),
              StringUtils.toStringAsDecimal(oldData?.MainNum),
              horizon: false,
              isForceCompare: _isForceCompare2);
        },
      );
      rowChildren.add(NumberOfApplications3);
      //已申请数量
      var Quantity3 = StatefulBuilder(
        builder: (contxet, setState) {
          var isRed = UiBase.isNotSame(
              StringUtils.toStringAsDecimal(data?.Quantity),
              StringUtils.toStringAsDecimal(oldData?.Quantity));
          isRed = false; //fixme 不做对比。
          return UiBase.itemWithSigleEdit(
              context, StringUtils.toStringAsDecimal(data?.Quantity),
              isAllowEmpty: true,
              isDecimal: true,
              readOnly: true,
              isNegative: false,
              isRed: isRed);
        },
      );
      rowChildren.add(Quantity3);
      if (isMT01) {
        //顿重
        var tons = StatefulBuilder(
          builder: (contxet, setState) {
            // var isRed = UiBase.isNotSame(data?.tons, oldData?.tons);
            // return UiBase.itemWithSigleEdit(context, data?.tons,
            //     isAllowEmpty: true,
            //     isDecimal: true,
            //     readOnly: true,
            //     isNegative: false,
            //     isRed: isRed);
            return UiBase.itemWithCompare(
                context,
                StringUtils.toStringAsDecimal(data?.tons),
                StringUtils.toStringAsDecimal(oldData?.tons),
                horizon: false,
                isForceCompare: _isForceCompare2);
          },
        );
        rowChildren.add(tons);
        //tonsprice 顿重单价
        var tonsprice = StatefulBuilder(
          builder: (contxet, setState) {
            // var isRed = UiBase.isNotSame(data?.tonsprice, oldData?.tonsprice);
            // return UiBase.itemWithSigleEdit(context, data?.tonsprice,
            //     isAllowEmpty: true,
            //     isDecimal: true,
            //     readOnly: true,
            //     isNegative: false,
            //     isRed: isRed);
            return UiBase.itemWithCompare(
                context,
                StringUtils.toStringAsDecimal(data?.tonsprice),
                StringUtils.toStringAsDecimal(oldData?.tonsprice),
                horizon: false,
                isForceCompare: _isForceCompare2);
          },
        );
        rowChildren.add(tonsprice);
      }
      if (isMT01) {
        //面积
        var StockArea = StatefulBuilder(
          builder: (contxet, setState) {
            return _text(context, "${data?.SubsidiaryNum}",
                oldText: "${oldData?.SubsidiaryNum}",
                isForceCompare: _isForceCompare2);
          },
        );
        rowChildren.add(StockArea);
        //areaprice 折算面积单价
        var areaprice = StatefulBuilder(
          builder: (contxet, setState) {
            // var one = _text(context, "${data?.areaprice}",
            //     oldText: "${oldData?.areaprice}");
            if (data.isChange()) {
              //fixme 优先以Change里的为标准。
              var one = _text(
                  context, "${StringUtils.toStringAsDecimal(data?.areaprice)}",
                  oldText: null);
              var isSame =
                  StringUtils.isSame(data?.areaprice, data?.ChangeAreaPrice);
              if (!isSame) {
                //fixme 不相同
                var two = _text(context,
                    "(${StringUtils.toStringAsDecimal(data?.ChangeAreaPrice)})",
                    isRed: true); //最新的，用红色表示。
                return Column(
                  children: [one, two],
                  mainAxisAlignment: MainAxisAlignment.center,
                );
              }
            }
            // return one;
            return UiBase.itemWithCompare(
                context, data?.areaprice, oldData?.areaprice,
                horizon: false, isForceCompare: _isForceCompare2);
          },
        );
        rowChildren.add(areaprice);
      }

      if (firstData.isPrice()) {
        //单价
        var Price = StatefulBuilder(
          builder: (contxet, setState) {
            // var one =
            //     _text(context, "${data?.Price}", oldText: "${oldData?.Price}");
            if (data.isChange()) {
              var isSame = StringUtils.isSame(data?.Price, data?.ChangePrice);
              if (!isSame) {
                var one = _text(
                    context, "${StringUtils.toStringAsDecimal(data?.Price)}",
                    oldText: null);
                //fixme 不相同
                var two = _text(context,
                    "(${StringUtils.toStringAsDecimal(data?.ChangePrice)})",
                    isRed: true); //最新的，用红色表示。
                return Column(
                  children: [one, two],
                  mainAxisAlignment: MainAxisAlignment.center,
                );
              }
            }
            // return one;
            return UiBase.itemWithCompare(context, data?.Price, oldData?.Price,
                horizon: false, isForceCompare: _isForceCompare2);
          },
        );
        rowChildren.add(Price);
      }
      //金额
      var Amount = StatefulBuilder(
        builder: (contxet, setState) {
          // return _text("${data?.Amount}", oldText: "${oldData?.Amount}");
          return UiBase.itemWithCompare(
              context,
              StringUtils.toStringAsDecimal(data?.Amount),
              StringUtils.toStringAsDecimal(oldData?.Amount),
              horizon: false,
              isForceCompare: _isForceCompare2);
        },
      );
      rowChildren.add(Amount);
      if (isMT01) {
        //质量等级
        var QualityGrade = StatefulBuilder(
          builder: (contxet, setState) {
            // var one = _text(context, "${data?.QualityGradeName}",
            //     oldText: "${oldData?.QualityGradeName}");
            // print(
            //     "QualityGradeName:${data?.QualityGradeName}\tQualityGrade:${data?.QualityGrade}\tChangeQualityGrade:\t${data?.ChangeQualityGrade}\t是否改变：${data.isChange()}\t旧：QualityGradeName:${oldData?.QualityGradeName}");
            if (data.isChange()) {
              var isSame = StringUtils.isSame(
                  data?.QualityGrade, data?.ChangeQualityGrade);
              if (!isSame) {
                var one =
                    _text(context, "${data?.QualityGradeName}", oldText: null);
                //fixme 不相同
                var two = _text(context, "(${data?.ChangeQualityGradeName})",
                    isRed: true); //最新的，用红色表示。
                return Column(
                  children: [one, two],
                  mainAxisAlignment: MainAxisAlignment.center,
                );
              }
            }
            // return one;
            return UiBase.itemWithCompare(
                context, data?.QualityGradeName, oldData?.QualityGradeName,
                horizon: false, isForceCompare: _isForceCompare2);
          },
        );
        rowChildren.add(QualityGrade);
      }
      //品牌
      var ManufacturerName = StatefulBuilder(
        builder: (contxet, setState) {
          // var one = _text(context, "${data?.ManufacturerName}",
          //     oldText: "${oldData?.ManufacturerName}");
          if (data.isChange()) {
            var isSame = StringUtils.isSame(
                data?.ManufacturerId, data?.ChangeManufacturerId);
            if (!isSame) {
              var one =
                  _text(context, "${data?.ManufacturerName}", oldText: null);
              //fixme 不相同
              var two = _text(context, "(${data?.ChangeManufacturerName})",
                  isRed: true); //最新的，用红色表示。
              return Column(
                children: [one, two],
                mainAxisAlignment: MainAxisAlignment.center,
              );
            }
          }
          // return one;
          return UiBase.itemWithCompare(
              context, data?.ManufacturerName, oldData?.ManufacturerName,
              horizon: false, isForceCompare: _isForceCompare2);
        },
      );
      rowChildren.add(ManufacturerName);
      //备注
      var ListBeizhu = _text(context, "${data?.ListBeizhu}",
          oldText: "${oldData?.ListBeizhu}", isForceCompare: _isForceCompare2);
      rowChildren.add(ListBeizhu);
      var tableRow = TableRow(
          // decoration: BoxDecoration(color: _getColor(_index + 1)),
          // decoration: BoxDecoration(color: _getColor(i)),
          children: rowChildren);
      children.add(tableRow);
    }
    var table = Table(
      border: TableBorder.symmetric(
          inside: BorderSide(
              color: _BorderColor, width: _width, style: BorderStyle.solid),
          outside: BorderSide.none),
      children: children,
      columnWidths: _columnWidths(),
      defaultVerticalAlignment: TableCellVerticalAlignment.middle,
    );
    return table;
  }

  ///获取库存数量
  static getStockNum(BuildContext context,
      StateSetter? CurrentInventorySetState, PurDemand data) {
    ///data?.StockNum
    MaterialModel.getStockNum(context, data, false, (value) {
      if (value.isSuccessForCode()) {
        CurrentInventorySetState?.call(() {
          data?.StockNum = value.StockNum;
          //print("物料请购库存：${data?.StockNum}");
        });
      }
    });
  }

  ///内部嵌套表格(序号)
  static Widget _totalSerial(BuildContext context) {
    List<Widget> titleChildren = [];
    titleChildren.add(_text(context, "")); //序号
    var table = Table(
      border: TableBorder.symmetric(
        inside: BorderSide(
            color: _BorderColor, width: _width, style: BorderStyle.solid),
      ),
      children: [
        TableRow(children: titleChildren),
      ],
      defaultVerticalAlignment: TableCellVerticalAlignment.middle,
    );
    return table;
  }

  ///内部嵌套表格(标题)；合计
  static Widget _totalAll(
      BuildContext context,
      List<PurContractListBean> allDatas,
      PurContractListBean firstData,
      bool isMT01) {
    var POMinNum = 0.0; //请购数量
    var MainNum = 0.0; //采购数量
    var tons = 0.0; //顿重
    var SubsidiaryNum = 0.0; //面积
    var Amount = 0.0; //金额

    var POMinNumStr = ""; //请购数量
    var MainNumStr = ""; //采购数量
    var tonsStr = ""; //顿重
    var SubsidiaryNumStr = ""; //面积
    var AmountStr = ""; //金额
    allDatas?.forEach((element) {
      try {
        var data = element.POMinNum;
        if (StringUtils.isNotEmpty(data)) {
          POMinNum = AcombinedUtils.add(POMinNum, data);
        }
      } catch (e) {}
      try {
        var data = element.MainNum;
        if (StringUtils.isNotEmpty(data)) {
          MainNum = AcombinedUtils.add(MainNum, data);
        }
      } catch (e) {}
      try {
        var data = element.tons;
        if (StringUtils.isNotEmpty(data)) {
          tons = AcombinedUtils.add(tons, data);
        }
      } catch (e) {}
      try {
        var data = element.SubsidiaryNum;
        if (StringUtils.isNotEmpty(data)) {
          SubsidiaryNum = AcombinedUtils.add(SubsidiaryNum, data);
        }
      } catch (e) {}
      try {
        var data = element.Amount;
        if (StringUtils.isNotEmpty(data)) {
          Amount = AcombinedUtils.add(Amount, data);
        }
      } catch (e) {}
    });
    POMinNumStr = NumUtil.strToDoubleStr(POMinNum.toString());
    MainNumStr = NumUtil.strToDoubleStr(MainNum.toString());
    tonsStr = NumUtil.strToDoubleStr(tons.toString());
    SubsidiaryNumStr = NumUtil.strToDoubleStr(SubsidiaryNum.toString());
    AmountStr = NumUtil.strToDoubleStr(Amount.toString());
    List<Widget> titleChildren = [];
    titleChildren.add(_text(context, "")); //请购单号
    titleChildren.add(_text(context, "")); //物料类型
    titleChildren.add(_text(context, "")); //物料名称
    titleChildren.add(_text(context, "")); //物料编码
    titleChildren.add(_text(context, "")); //型号
    if (isMT01) {
      titleChildren.add(_text(context, "")); //规格
    } else {
      if (firstData.Iswidth2()) {
        titleChildren.add(_text(context, "")); //宽
      }
      if (firstData.Isheight2()) {
        titleChildren.add(_text(context, "")); //高
      }
      if (firstData.Islength2()) {
        titleChildren.add(_text(context, "")); //长
      }
      if (firstData.Isthickness2()) {
        titleChildren.add(_text(context, "")); //厚
      }
      if (firstData.Isquantity2()) {
        titleChildren.add(_text(context, "")); //数量
      }
      if (!firstData.isMT01() && isNewUnit) {
        //辅料，五金；显示；包数量，和每包数量。
        titleChildren.add(_text(context, "", isStart: false)); //包数量
        titleChildren.add(_text(context, "", isStart: false)); //每包数量
      }
    }
    titleChildren
        .add(_text(context, POMinNumStr, isStart: false)); //fixme(需要合计) 请购数量
    titleChildren.add(_text(context, "", isStart: false)); //单位
    titleChildren
        .add(_text(context, MainNumStr, isStart: false)); //fixme(需要合计) 采购数量
    titleChildren.add(_text(context, "", isStart: false)); //已申请数量
    if (isMT01) {
      titleChildren.add(_text(context, tonsStr)); //fixme(需要合计) 顿重
      titleChildren.add(_text(context, "")); //顿重单价
    }
    if (isMT01) {
      titleChildren.add(_text(context, SubsidiaryNumStr)); //fixme(需要合计) 面积
      titleChildren.add(_text(context, "")); //折算面积单价
    }
    if (firstData.isPrice()) {
      titleChildren.add(_text(context, "", isStart: false)); //单价
    }
    titleChildren.add(_text(context, AmountStr)); //fixme(需要合计) 金额
    if (isMT01) {
      titleChildren.add(_text(context, "")); //质量等级
    }
    titleChildren.add(_text(context, "")); //品牌
    titleChildren.add(_text(context, "")); //备注
    var table = Table(
      border: TableBorder.symmetric(
        inside: BorderSide(
            color: _BorderColor, width: _width, style: BorderStyle.solid),
      ),
      children: [
        TableRow(children: titleChildren),
      ],
      columnWidths: _columnWidths(),
      defaultVerticalAlignment: TableCellVerticalAlignment.middle,
    );
    return table;
  }

  //fixme 条目颜色背景
  static Color _getColor(int i) {
    Color _color = _backgroundColorWithWhite;
    //print("=============$i ${i%2}");
    if (i % 2 == 0) {
      _color = _backgroundColorWithGrey;
    }
    return _color;
  }

  //文本
  static Widget _text(
    BuildContext context,
    String? text, {
    bool isStart = false,
    bool isRed = false,
    String? oldText,
    bool isForceCompare = false,
  }) {
    // print("================================$text\t$oldText\t$_isForceCompare");
    if ((StringUtils.isNotEmpty(text) && StringUtils.isNotEmpty(oldText)) ||
        isForceCompare) {
      return UiBase.itemWithCompare(context, text, oldText,
          horizon: false, isForceCompare: isForceCompare);
    }
    // return Center(
    //   child: Text(text ?? ""),
    // );
    Widget child;
    var textStyle = AppStyle.textStyleWithCard();
    if (isRed) {
      textStyle = AppStyle.textStyleWithCardRed();
    } else {
      if (StringUtils.isNotEmpty(oldText)) {
        var b = UiBase.isNotSame(text, oldText);
        if (b) {
          //fixme 文本不相同；红色标注。
          textStyle = AppStyle.textStyleWithCardRed();
        }
      }
    }
    if (isStart) {
      var textKey = Text(
        text ?? "",
        style: textStyle,
      );
      var value = "*";
      var startText = Text(
        value,
        softWrap: true,
        style: AppStyle.textStyleWithCardRed(),
      );
      child = SizedBox(
        child: Row(
          children: [textKey, startText],
          mainAxisAlignment: MainAxisAlignment.center,
        ),
        width: 120,
      );
    } else {
      child = Text(
        text ?? "",
        style: textStyle,
      );
    }
    return Center(
      child: ConstrainedBox(
        constraints: BoxConstraints(
          minHeight: 36.0, //最小高度
        ),
        child: Center(
          child: child,
        ),
      ),
    );
  }

  //复选框
  //isChecked 是否选中
  //isEnable 是否可操作
  //onChanged 选中回调
  static Widget _checkbox(bool isChecked,
      {bool isEnable = true, Function(bool)? onChanged}) {
    Color activeColor = Colors.blueAccent;
    Color inactiveColor = Colors.black;
    if (!isEnable) {
      //不可用，颜色变暗。
      activeColor = Colors.black12;
      inactiveColor = Colors.black12;
    }
    return Container(
      alignment: Alignment.center,
      // height: 30,
      // width: 30,
      padding: EdgeInsets.zero,
      margin: EdgeInsets.zero,
      child: CircleCheckbox(
        isEnable: isEnable,
        value: isChecked,
        //value 是否选中
        width: 20,
        //width 宽度
        height: 20,
        //height 高度
        activeColor: activeColor,
        //activeColor 选中时背景颜色
        inactiveColor: inactiveColor,
        //inactiveColor 未选中时颜色
        style: CircleCheckboxStyle.tick_hollow,
        //circle_point 圆点样式
        //checked: , 自定义选中组件；fixme 优先级比以上属性设置要高。
        //unChecked: ,自定义未选中组件
        onChanged: (bool) {
          //选中状态改变时回调，如点击时。
          //选中状态改变时回调。
          //setState(() {});
          if (isEnable) {
            onChanged?.call(bool);
          }
        },
      ),
    );
  }

  ///按钮
  static Widget _materialButton(String text,
      {VoidCallback? onPressed,
      double radius = 5,
      double height = 35,
      double width = 50,
      Color color = Colors.blueAccent,
      Color textColor = Colors.white,
      double fontSize = 14,
      EdgeInsetsGeometry margin = const EdgeInsets.only(left: 8, right: 8),
      EdgeInsetsGeometry padding =
          const EdgeInsets.only(left: 16, right: 16)}) {
    return Container(
      margin: margin,
      child: MaterialButton(
        padding: padding,
        height: height,
        minWidth: width,
        onPressed: () {
          onPressed?.call();
        },
        //label 右边控件（一般为文本），不能为空
        color: color,
        //color 按钮颜色
        splashColor: Colors.black12,
        //splashColor 点击时，飞溅扩散的颜色
        //highlightColor: Colors.red, //highlightColor 点击时按钮颜色
        colorBrightness: Brightness.light,
        //colorBrightness 按钮亮度；Brightness.dark 暗系风格;Brightness.light 高亮(默认)
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(radius))),
        //shape 形状
        textColor: Colors.white,
        //文本默认颜色
        child: Text(
          text,
          style: TextStyle(
            color: textColor,
            fontSize: fontSize,
          ),
        ), //fixme 子控件
      ),
    );
  }
}
